﻿Imports System.Messaging
Imports System.Diagnostics
Imports DNBReadQSaveToDB_WS.DNBService

Public Class DNBReadQSaveToDB_WS

    'define static local private queue
    Private Shared _mq As MessageQueue
    Private Shared _mq1 As MessageQueue
    Private Shared _mq2 As MessageQueue
    Private Shared _mq3 As MessageQueue
    Private Shared _mq4 As MessageQueue
    Private Shared _mq5 As MessageQueue
    Private Shared _mq6 As MessageQueue
    Private Shared _mq7 As MessageQueue
    Private Shared _mq8 As MessageQueue
    Private Shared _mq9 As MessageQueue
    Private Shared _errorq As MessageQueue
    


    Private Shared ReadOnly Property mq() As MessageQueue
        Get
            If _mq Is Nothing Then
                If Not MessageQueue.Exists(My.Settings.QueueName.ToString) Then
                    MessageQueue.Create(My.Settings.QueueName.ToString, True)
                End If
                _mq = New MessageQueue(My.Settings.QueueName.ToString, QueueAccessMode.ReceiveAndAdmin)
                _mq.Formatter = New BinaryMessageFormatter()
            End If
            Return _mq
        End Get
    End Property

    Private Shared ReadOnly Property mq1() As MessageQueue
        Get
            If _mq1 Is Nothing Then
                If Not MessageQueue.Exists(My.Settings.QueueName1.ToString) Then
                    MessageQueue.Create(My.Settings.QueueName1.ToString, True)
                End If
                _mq1 = New MessageQueue(My.Settings.QueueName1.ToString, QueueAccessMode.ReceiveAndAdmin)
                _mq1.Formatter = New BinaryMessageFormatter()
            End If
            Return _mq1
        End Get
    End Property
    Private Shared ReadOnly Property mq2() As MessageQueue
        Get
            If _mq2 Is Nothing Then
                If Not MessageQueue.Exists(My.Settings.QueueName2.ToString) Then
                    MessageQueue.Create(My.Settings.QueueName2.ToString, True)
                End If
                _mq2 = New MessageQueue(My.Settings.QueueName2.ToString, QueueAccessMode.ReceiveAndAdmin)
                _mq2.Formatter = New BinaryMessageFormatter()
            End If
            Return _mq2
        End Get
    End Property
    Private Shared ReadOnly Property mq3() As MessageQueue
        Get
            If _mq3 Is Nothing Then
                If Not MessageQueue.Exists(My.Settings.QueueName3.ToString) Then
                    MessageQueue.Create(My.Settings.QueueName3.ToString, True)
                End If
                _mq3 = New MessageQueue(My.Settings.QueueName3.ToString, QueueAccessMode.ReceiveAndAdmin)
                _mq3.Formatter = New BinaryMessageFormatter()
            End If
            Return _mq3
        End Get
    End Property
    Private Shared ReadOnly Property mq4() As MessageQueue
        Get
            If _mq4 Is Nothing Then
                If Not MessageQueue.Exists(My.Settings.QueueName4.ToString) Then
                    MessageQueue.Create(My.Settings.QueueName4.ToString, True)
                End If
                _mq4 = New MessageQueue(My.Settings.QueueName4.ToString, QueueAccessMode.ReceiveAndAdmin)
                _mq4.Formatter = New BinaryMessageFormatter()
            End If
            Return _mq4
        End Get
    End Property
    Private Shared ReadOnly Property mq5() As MessageQueue
        Get
            If _mq5 Is Nothing Then
                If Not MessageQueue.Exists(My.Settings.QueueName5.ToString) Then
                    MessageQueue.Create(My.Settings.QueueName5.ToString, True)
                End If
                _mq5 = New MessageQueue(My.Settings.QueueName5.ToString, QueueAccessMode.ReceiveAndAdmin)
                _mq5.Formatter = New BinaryMessageFormatter()
            End If
            Return _mq5
        End Get
    End Property
    Private Shared ReadOnly Property mq6() As MessageQueue
        Get
            If _mq6 Is Nothing Then
                If Not MessageQueue.Exists(My.Settings.QueueName6.ToString) Then
                    MessageQueue.Create(My.Settings.QueueName6.ToString, True)
                End If
                _mq6 = New MessageQueue(My.Settings.QueueName6.ToString, QueueAccessMode.ReceiveAndAdmin)
                _mq6.Formatter = New BinaryMessageFormatter()
            End If
            Return _mq6
        End Get
    End Property
    Private Shared ReadOnly Property mq7() As MessageQueue
        Get
            If _mq7 Is Nothing Then
                If Not MessageQueue.Exists(My.Settings.QueueName7.ToString) Then
                    MessageQueue.Create(My.Settings.QueueName7.ToString, True)
                End If
                _mq7 = New MessageQueue(My.Settings.QueueName7.ToString, QueueAccessMode.ReceiveAndAdmin)
                _mq7.Formatter = New BinaryMessageFormatter()
            End If
            Return _mq7
        End Get
    End Property
    Private Shared ReadOnly Property mq8() As MessageQueue
        Get
            If _mq8 Is Nothing Then
                If Not MessageQueue.Exists(My.Settings.QueueName8.ToString) Then
                    MessageQueue.Create(My.Settings.QueueName8.ToString, True)
                End If
                _mq8 = New MessageQueue(My.Settings.QueueName8.ToString, QueueAccessMode.ReceiveAndAdmin)
                _mq8.Formatter = New BinaryMessageFormatter()
            End If
            Return _mq8
        End Get
    End Property
    Private Shared ReadOnly Property mq9() As MessageQueue
        Get
            If _mq9 Is Nothing Then
                If Not MessageQueue.Exists(My.Settings.QueueName9.ToString) Then
                    MessageQueue.Create(My.Settings.QueueName9.ToString, True)
                End If
                _mq9 = New MessageQueue(My.Settings.QueueName9.ToString, QueueAccessMode.ReceiveAndAdmin)
                _mq9.Formatter = New BinaryMessageFormatter()
            End If
            Return _mq9
        End Get
    End Property

    Public Shared Sub CheckIfErrorQExists()
        If Not MessageQueue.Exists(My.Settings.ErrorQueueName) Then
            Try
                MessageQueue.Create(My.Settings.ErrorQueueName)
            Catch e As MessageQueueException
                If e.MessageQueueErrorCode = _
                    MessageQueueErrorCode.AccessDenied Then

                    WriteToEventLog("Access is denied. " _
                        + "Queue might be a system queue.")
                End If

                ' Handle other sources of exceptions as necessary.

            End Try
        End If
    End Sub

   

    Private Sub mq_ReceiveCompleted(sender As Object, e As ReceiveCompletedEventArgs)
        Dim Client As DNBService.DnB10Client = Nothing
        Dim bizDataset As New BizDataSetTableAdapters.bizDataTableAdapter
        Dim dnbDataTable As BizDataSet.bizDataDataTable
        Dim dnbDataRow As BizDataSet.bizDataRow

        Client = New DnB10Client
        'queue that have received a message
        Dim cmq As MessageQueue = DirectCast(sender, MessageQueue)

        cmq.Formatter = New XmlMessageFormatter(New Type() {GetType(vDNBData)})
        Dim _dnbdata As New vDNBData
        Try
            'a message we have received (it is already removed from queue)
            'here you can process a message
            Dim msg As Message = cmq.EndReceive(e.AsyncResult)

            _dnbdata = msg.Body

            With _dnbdata
                Dim optionalReturnFields As New GetCompanyDetailOptionalDataRequest
                optionalReturnFields.uniqueId = .CompanyId
                optionalReturnFields.optionalResponseFields = New OptionalDataResponseFields
                optionalReturnFields.optionalResponseFields.includeIndustries = True
                optionalReturnFields.optionalResponseFields.includeURLs = True
                optionalReturnFields.optionalResponseFields.includeKeyNumbers = True
                optionalReturnFields.optionalResponseFields.includeLocations = True
                optionalReturnFields.optionalResponseFields.includePhones = True
                optionalReturnFields.optionalResponseFields.includeRankings = True
                'optionalReturnFields.optionalResponseFields.includeSocialMedia = True
                optionalReturnFields.optionalResponseFields.includeStocks = True
                optionalReturnFields.optionalResponseFields.includeURLs = True

                Dim primaryURLs As String = String.Empty
                Dim fulldescription As String = String.Empty
                Dim companyType As String = String.Empty
                Dim lineOfBusiness As String = String.Empty
                Dim primaryDnBIC As String = String.Empty
                Dim allNAICS As String = String.Empty
                Dim allUSSIC As String = String.Empty
                Dim naics As String = String.Empty
                Dim longitude As String = String.Empty
                Dim latitude As String = String.Empty
                Dim womenOwned As Boolean = Nothing
                Dim minorityOwned As Boolean = Nothing
                Dim ownedOrLeased As String = String.Empty

                Dim optionalResponseFields As New GetCompanyDetailOptionalDataResponse
                Try
                    optionalResponseFields = Client.GetCompanyDetailOptionalData(If(.CompanyId Mod 2 = 0, My.Settings.APIKey, My.Settings.APIKey2), "", "", optionalReturnFields)
                Catch ex As Exception
                    Throw New Exception("DnBData - Failed to retrieve optional fields for comapany id : " & .CompanyId & ControlChars.Lf & ex.Message.ToString)
                End Try

                If Not optionalResponseFields.return Is Nothing Then
                    With optionalResponseFields.return
                        primaryURLs = If(optionalResponseFields.return.primaryURLs.Count > 0, optionalResponseFields.return.primaryURLs(0).url, "")
                        fulldescription = If(.fulldescription.Length > 350, Left(.fulldescription, 350), .fulldescription)
                        companyType = If(.companyType Is Nothing, "", .companyType)
                        lineOfBusiness = If(.industries.lineOfBusiness Is Nothing, "", .industries.lineOfBusiness)
                        primaryDnBIC = If(.industries.primaryDnBIC Is Nothing, "", .industries.primaryDnBIC)
                        allNAICS = If(.industries.allNAICS.First Is Nothing, "", .industries.allNAICS.First.description)
                        allUSSIC = If(.industries.allUSSIC.First Is Nothing, "", .industries.allUSSIC.First.description)
                        naics = If(.industries.allNAICS.First.naics Is Nothing, "", .industries.allNAICS.First.naics)
                        longitude = If(.locations.First.longitude Is Nothing, "", .locations.First.longitude.ToString)
                        latitude = If(.locations.First.latitude Is Nothing, "", .locations.First.latitude.ToString)
                        womenOwned = .womenOwned
                        minorityOwned = .minorityOwned
                        ownedOrLeased = If(.ownedOrLeased Is Nothing, "", .ownedOrLeased)
                    End With
                End If
                If Not bizDataset.CompanyIdExist(.CompanyId) > 0 Then
                    bizDataset.Insert(.CompanyId _
                                                     , .CompanyName _
                                                     , .Address1 _
                                                     , .City _
                                                     , .StateOrProvince _
                                                     , .PostalCode _
                                                     , .Phone _
                                                     , .offset _
                                                     , .LocationType _
                                                     , .Duns _
                                                     , .ParentDuns _
                                                     , .UltimateParentDuns _
                                                     , .Sales _
                                                     , .DBA _
                                                     , .CountryID _
                                                     , primaryURLs _
                                                     , fulldescription _
                                                     , companyType _
                                                     , String.Empty _
                                                     , String.Empty _
                                                     , lineOfBusiness _
                                                     , primaryDnBIC _
                                                     , allNAICS _
                                                     , allUSSIC _
                                                     , naics _
                                                     , longitude _
                                                     , latitude _
                                                     , womenOwned _
                                                     , minorityOwned _
                                                     , ownedOrLeased _
                                                     , String.Empty _
                                                     , String.Empty _
                                                     , String.Empty _
                                                     , String.Empty _
                                                     , DateTime.Now)
                Else
                    bizDataset.UpdateBizDataSet(.CompanyName _
                                                     , .Address1 _
                                                     , .City _
                                                     , .StateOrProvince _
                                                     , .PostalCode _
                                                     , .Phone _
                                                     , .offset _
                                                     , .LocationType _
                                                     , .Duns _
                                                     , .ParentDuns _
                                                     , .UltimateParentDuns _
                                                     , .Sales _
                                                     , .DBA _
                                                     , .CountryID _
                                                     , primaryURLs _
                                                     , fulldescription _
                                                     , companyType _
                                                     , String.Empty _
                                                     , String.Empty _
                                                     , lineOfBusiness _
                                                     , primaryDnBIC _
                                                     , allNAICS _
                                                     , allUSSIC _
                                                     , naics _
                                                     , longitude _
                                                     , latitude _
                                                     , womenOwned _
                                                     , minorityOwned _
                                                     , ownedOrLeased _
                                                     , String.Empty _
                                                     , String.Empty _
                                                     , String.Empty _
                                                     , String.Empty _
                                                     , DateTime.Now _
                                                     , .CompanyId)
                End If
            End With


        Catch eReceive As MessageQueueException
            WriteToEventLog(eReceive.Message.ToString, _dnbdata)
            'MsgBox(ex.Message.ToString, MsgBoxStyle.OkOnly)

        Catch ex As Exception
            WriteToEventLog(ex.Message.ToString, _dnbdata)

        End Try
        'refresh queue just in case any changes occurred (optional)
        cmq.Refresh()
        'tell MessageQueue to receive next message when it arrives
        cmq.BeginReceive()

    End Sub

    Public Sub New()
        InitializeComponent()
        'event to process received message 
        AddHandler mq.ReceiveCompleted, AddressOf mq_ReceiveCompleted
        AddHandler mq1.ReceiveCompleted, AddressOf mq_ReceiveCompleted
        AddHandler mq2.ReceiveCompleted, AddressOf mq_ReceiveCompleted
        AddHandler mq3.ReceiveCompleted, AddressOf mq_ReceiveCompleted
        AddHandler mq4.ReceiveCompleted, AddressOf mq_ReceiveCompleted
        AddHandler mq5.ReceiveCompleted, AddressOf mq_ReceiveCompleted
        AddHandler mq6.ReceiveCompleted, AddressOf mq_ReceiveCompleted
        AddHandler mq7.ReceiveCompleted, AddressOf mq_ReceiveCompleted
        AddHandler mq8.ReceiveCompleted, AddressOf mq_ReceiveCompleted
        AddHandler mq9.ReceiveCompleted, AddressOf mq_ReceiveCompleted
    End Sub

    Protected Overrides Sub OnStart(ByVal args() As String)
        CheckIfErrorQExists()
        ' Add code here to start your service. This method should set things
        ' in motion so your service can do its work.
        If mq IsNot Nothing Then
            mq.BeginReceive()
        End If
        If mq1 IsNot Nothing Then
            mq1.BeginReceive()
        End If
        If mq2 IsNot Nothing Then
            mq2.BeginReceive()
        End If
        If mq3 IsNot Nothing Then
            mq3.BeginReceive()
        End If
        If mq4 IsNot Nothing Then
            mq4.BeginReceive()
        End If
        If mq5 IsNot Nothing Then
            mq5.BeginReceive()
        End If
        If mq6 IsNot Nothing Then
            mq6.BeginReceive()
        End If
        If mq7 IsNot Nothing Then
            mq7.BeginReceive()
        End If
        If mq8 IsNot Nothing Then
            mq8.BeginReceive()
        End If
        If mq9 IsNot Nothing Then
            mq9.BeginReceive()
        End If
    End Sub

    Protected Overrides Sub OnStop()
        ' Add code here to perform any tear-down necessary to stop your service.
        If mq IsNot Nothing Then
            mq.Close()
        End If
    
        If mq1 IsNot Nothing Then
            mq1.Close()
        End If

        If mq2 IsNot Nothing Then
            mq2.Close()
        End If

        If mq3 IsNot Nothing Then
            mq3.Close()
        End If

        If mq4 IsNot Nothing Then
            mq4.Close()
        End If

        If mq5 IsNot Nothing Then
            mq5.Close()
        End If

        If mq6 IsNot Nothing Then
            mq6.Close()
        End If

        If mq7 IsNot Nothing Then
            mq7.Close()
        End If

        If mq8 IsNot Nothing Then
            mq8.Close()
        End If

        If mq9 IsNot Nothing Then
            mq9.Close()
        End If

        
    End Sub
    Public Shared Function WriteToEventLog(ByVal Entry As String, _
                                           Optional ByVal _dnbData As vDNBData = Nothing, _
    Optional ByVal AppName As String = "DNB", _
    Optional ByVal EventType As  _
    EventLogEntryType = EventLogEntryType.Information, _
    Optional ByVal LogName As String = "Application") As Boolean

        '*************************************************************
        'PURPOSE: Write Entry to Event Log using VB.NET
        'PARAMETERS: Entry - Value to Write
        '            AppName - Name of Client Application. Needed 
        '              because before writing to event log, you must 
        '              have a named EventLog source. 
        '            EventType - Entry Type, from EventLogEntryType 
        '              Structure e.g., EventLogEntryType.Warning, 
        '              EventLogEntryType.Error
        '            LogName: Name of Log (System, Application; 
        '              Security is read-only) If you 
        '              specify a non-existent log, the log will be
        '              created

        'RETURNS:   True if successful, false if not

        'EXAMPLES: 
        '1. Simple Example, Accepting All Defaults
        '    WriteToEventLog "Hello Event Log"

        '2.  Specify EventSource, EventType, and LogName
        '    WriteToEventLog("Danger, Danger, Danger", "MyVbApp", _
        '                      EventLogEntryType.Warning, "System")
        '
        'NOTE:     EventSources are tightly tied to their log. 
        '          So don't use the same source name for different 
        '          logs, and vice versa
        '******************************************************

        Dim objEventLog As New EventLog()
        Dim mqTran As New MessageQueueTransaction()
        mqTran.Begin()

        Try
            'Register the App as an Event Source
            If Not objEventLog.SourceExists(AppName) Then

                objEventLog.CreateEventSource(AppName, LogName)
            End If
            'objEventLog.Log = "TEST"
            objEventLog.Source = AppName

            'WriteEntry is overloaded; this is one
            'of 10 ways to call it
            objEventLog.WriteEntry(Entry, EventType)



            Dim _errorq As New MessageQueue(My.Settings.ErrorQueueName)
            _errorq.Send(_dnbData, mqTran)
            mqTran.Commit()

            Return True
        Catch Ex As Exception
            Return False

        End Try

    End Function


End Class
